<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>图书管理</title>
    <link rel="stylesheet" href="${pageContext.request.contextPath}/static/layui/css/layui.css">
    <link rel="stylesheet" href="${pageContext.request.contextPath}/static/layui/css/modules/layer/default/layer.css">
    <script src="${pageContext.request.contextPath}/static/layui/layui.js"></script>
    <script src="${pageContext.request.contextPath}/static/jquery-3.5.1.min.js"></script>
    <script src="${pageContext.request.contextPath}/static/layer/layer.js"></script>
    <script src="${pageContext.request.contextPath}/static/layui/xm-select.js"></script>
    <style>
        *{
            padding: 0px;
        }
        .layui-table-cell{
            text-align:center;
            height: auto;
            white-space: normal;
        }
        .layui-table img{
            width:200px;
            max-height: 200px;
        }
        .layui-form-select dl { max-height:250px; }
        img[src=""],img:not([src]){
            opacity:0;
        }
    </style>
</head>
<body>
<fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
    <legend><span style="font-size: xx-large;font-weight: bold;"> 图书管理</span></legend>
</fieldset>
<div class="layui-container">
    <div>
        <form class="layui-form" action="">
            <div class="layui-row layui-col-space30">
                <div class="layui-col-md3">
                    <input class="layui-input" id="search-title" autocomplete="off"  placeholder="请输入书名">
                </div>
                <div class="layui-col-md3">
                    <input class="layui-input" id="search-press" autocomplete="off"  placeholder="请输入出版社">
                </div>
                <div class="layui-col-md2">
                    <input class="layui-input" id="search-author" autocomplete="off"  placeholder="请输入作者名">
                </div>
                <div class="layui-col-md3">
                    <div id="search-type" class="xm-select-demo"></div>
                </div>
            <div class="layui-row layui-col-space20">
                <div class="layui-col-md2">
                    <input type="text" id="search-minPrice" placeholder="最低价格" autocomplete="off" class="layui-input">
                </div>
                <div class="layui-col-md2">
                    <input type="text" id="search-maxPrice" placeholder="最高价格" autocomplete="off" class="layui-input">
                </div>
                <div class="layui-col-md3">
                     <input type="checkbox" id="search-stock" checked="" name="open" lay-skin="switch" lay-filter="switchTest" lay-text="现有库存|现无库存">
                </div>
                <div class="layui-col-md3 layui-col-md-offset2">
                    <button id="searchBtn" type="button" class="layui-btn" lay-filter="formDemo">搜索</button>
                    <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                </div>
            </div>
            </div>
        </form>
    </div>
    <div class="layui-row">
        <table class="layui-hide" id="bookTable" lay-skin="line" lay-filter="bookTable">
        </table>
    </div>
</div>

<script type="text/html" id="toolbar">
    <div class="layui-btn-container">
        <button lay-event="deleteBooks" class="layui-btn layui-btn-danger">删除选中行</button>
        <button lay-event="saveBook" class="layui-btn layui-btn-normal">新增</button>
    </div>
</script>
<script type="text/html" id="bar">
    <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a><br/>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="delete">删除</a>
</script>
<script>
    var searchType = xmSelect.render({
        el: '#search-type',
        tips: '类别',
        data: [
            <c:forEach items="${applicationScope.typeList}" var="a">
                {name: '${a.value}',value: '${a.orderNo}', selected: true},
            </c:forEach>
        ]
    })
    layui.use(['table','form'], function(){
        var table = layui.table;
        var form = layui.form;

        $("#save_imgFile").change(function (){
            if(this.files.length){
                let file = this.files[0];
                let reader = new FileReader();
                reader.onload = function(){
                    // 当 FileReader 读取文件时候，读取的结果会放在 FileReader.result 属性中
                    $("#preview_img1").attr("src",this.result);
                };
                reader.readAsDataURL(file);
            }

        });

        $("#edit_imgFile").change(function (){
            $("#preview_img2").attr("src","");
            if(this.files.length){
                let file = this.files[0];
                let reader = new FileReader();
                reader.onload = function(){
                    // 当 FileReader 读取文件时候，读取的结果会放在 FileReader.result 属性中
                    $("#preview_img2").attr("src",this.result);
                };
                reader.readAsDataURL(file);
            }

        });

        $("#searchBtn").click(function (){
            reload();
        })

        var tableIns = table.render({
            elem: '#bookTable'
            ,url:'${pageContext.request.contextPath}/book/getBooksByCondition.do'
            ,toolbar: '#toolbar'
            ,where: {
                "title": $('#search-title').val(),
                "press": $('#search-press').val(),
                "author": $('#search-author').val(),
                "minPrice": $('#search-minPrice').val(),
                "maxPrice": $('#search-maxPrice').val(),
                "stock": $('#search-stock').is(":checked"),
                "type": searchType.getValue('name')
            }
            ,defaultToolbar: []
            ,page: true
            ,limits: [5,10,20]
            ,limit: 10
            ,parseData: function(res){
                var result;
                if(this.page.curr){
                    result = res.data.slice(this.limit*(this.page.curr-1),this.limit*this.page.curr);
                }
                else{
                    result=res.data.slice(0,this.limit);
                }
                return {
                    "code": res.code,
                    "msg": res.msg,
                    "count": res.count,
                    "data": result
                };
            }
            ,cols: [[
                {type:'checkbox', fixed: 'left'}
                ,{field:'id',title: 'ID',hide: true}
                ,{field:'title',width: 150, title: '书籍名'}
                ,{field:'serialNumber',width: 150, title: '图书编号'}
                ,{field:'img', title: '图片',width: 130, templet: function(d){
                        var fileName=d.img;
                        return '<div><img src="/static/image/'+fileName+'" alt="暂无图片"></div>'
                    }}
                ,{field:'press',width: 100, title: '出版社'}
                ,{field:'author',width: 100,title: '作者'}
                ,{field:'type',width: 100, title: '类别'}
                ,{field:'location',width: 100, title: '位置'}
                ,{field:'price',width: 100, title: '价格'}
                ,{field:'stock',width: 100,title: '库存'}
                ,{field:'borrows',width: 100,title: '借出'}
                ,{title: '操作',fixed: 'right',width: 100, toolbar: '#bar'}
            ]]
            ,done: function (res, curr, count) {
                //初始化高度，使得冻结行表体高度一致
                $(".layui-table-body  tr").each(function (index, val) {
                    $($(".layui-table-fixed .layui-table-body table tr")[index]).height(110);
                });
                //动态监听表体高度变化，冻结行跟着改变高度
                $(".layui-table-body  tr").resize(function () {
                    $(".layui-table-body  tr").each(function (index, val) {
                        $($(".layui-table-fixed .layui-table-body table tr")[index]).height($(val).height());
                    });
                });
                $(".layui-table-header  tr").resize(function () {
                    $(".layui-table-header  tr").each(function (index, val) {
                        $($(".layui-table-fixed .layui-table-header table tr")[index]).height($(val).height());
                    });
                });
                //初始化高度，使得冻结行表头高度一致
                $(".layui-table-header  tr").each(function (index, val) {
                    $($(".layui-table-fixed .layui-table-header table tr")[index]).height($(val).height());
                });
            }
        });

        var reNumber = /^[0-9]\d*$/;
        var reLocation = /^[A-Z]-[1-5]-0|[1-9]|[1-4][0-9]$/;

        //监听工具条
        table.on('tool(bookTable)', function(obj){
            var data = obj.data;
            switch(obj.event){
                case 'delete':
                    layer.confirm('真的删除么', function(index){
                        if(data.borrows*1!==0){
                            layer.msg("该图书有借出，无法删除");
                            return false;
                        }
                        $.ajax({
                            url:"${pageContext.request.contextPath}/book/deleteBookById.do",
                            data:{
                                "id" : data.id
                            },
                            type:"post",
                            dataType:"json",
                            success:function (n){
                                if(n.success){
                                    reload();
                                }else {
                                    layer.msg("删除"+data.title+"失败,"+n.msg);
                                }
                            }
                        });
                        layer.close(index);
                    });
                    break;
                case 'edit':
                    layer.open({
                        type: 1,
                        area: ['800px', '560px'],
                        shadeClose: true, //点击遮罩关闭
                        title: '修改图书',
                        btn: ['确定', '取消'],
                        content: $('#editBookFrame'),
                        success: function (index, layero){
                            console.log(data);
                            $("#edit-title").val(data.title);
                            $("#edit_imgFile").val("");
                            $("#preview_img2").attr("src","/static/image/"+data.img);
                            $("#edit-press").val(data.press);
                            $("#edit-author").val(data.author);
                            $("#edit-price").val(data.price);
                            $("#edit-type").val(data.type);
                            $("#edit-stock").val(data.stock);
                            $("#edit-borrows").val(data.borrows);
                            $("#edit-location").val(data.location);
                            form.render();
                        },
                        yes: function (index, layero){
                            var title = $.trim($("#edit-title").val());
                            var press = $.trim($("#edit-press").val());
                            var author = $.trim($("#edit-author").val());
                            var price = $.trim($("#edit-price").val());
                            var type = $.trim($("#edit-type").val());
                            var stock = $.trim($("#edit-stock").val());
                            var borrows = $.trim($("#edit-borrows").val());
                            var location = $.trim($("#edit-location").val());
                            if(title===''){
                                layer.msg("请输入图书名");
                                return false;
                            }
                            if(!(reNumber.test(price))){
                                layer.msg("请输入正确的价格");
                                return false;
                            }
                            if(!(reNumber.test(stock))){
                                layer.msg("请输入正确的库存数量");
                                return false;
                            }
                            if(!(reNumber.test(borrows))){
                                layer.msg("请输入正确的已借数量");
                                return false;
                            }
                            if(borrows>stock){
                                layer.msg("已借数量不得大于库存数量");
                                return false;
                            }
                            if(!(reLocation.test(location))){
                                layer.msg("请输入正确的位置信息");
                                return false;
                            }

                            var formFile = new FormData(document.getElementById('editBookForm'));
                            formFile.append("id", data.id);
                            formFile.append("img", data.img);
                            formFile.append("title", title);
                            formFile.append("press", press);
                            formFile.append("author", author);
                            formFile.append("price", price);
                            formFile.append("type", type);
                            formFile.append("stock", stock);
                            formFile.append("borrows", borrows);
                            formFile.append("location", location);
                            $.ajax({
                                url : '${pageContext.request.contextPath}/book/updateBook.do',
                                type : 'post',
                                dataType : 'json',
                                data : formFile,
                                cache: false,
                                processData: false,   // 用于对参数进行序列化处理，这里必须设为false
                                contentType:false,
                                success : function(n) {
                                    if (n.success) {
                                        layer.msg("更新图书《"+title+"》成功");
                                        reload();
                                        layer.close(index);
                                    }else {
                                        layer.msg("更新图书《"+title+"》失败,"+n.msg);
                                    }
                                }
                            });
                        },
                        end: function (res) {
                            $("#editBookFrame").css("display",'none');
                        }
                    });
                    break;
            };
        });
        table.on('toolbar(bookTable)', function(obj){
            var checkStatus = table.checkStatus(obj.config.id);
            switch(obj.event){
                case 'deleteBooks':
                    var data = checkStatus.data;
                    var size = data.length;
                    console.log(data);
                    if(size != 0){
                        layer.confirm('真的删除么', function(index){
                            for(let i = 0; i < size; i++){
                                if(data[i].borrows*1!==0){
                                    layer.msg("该图书有借出，无法删除");
                                    return false;
                                }
                                $.ajax({
                                    url:"${pageContext.request.contextPath}/book/deleteBookById.do",
                                    data:{
                                        "id" : data[i].id
                                    },
                                    async:false,
                                    type:"post",
                                    dataType:"json",
                                    success:function (n){
                                        if(!n.success){
                                            layer.msg("删除"+data[i].title+"失败,"+n.msg);
                                        }
                                    }
                                });
                            }
                            layer.close(index);
                            reload();
                        });
                    }else {
                        layer.msg("请勾选要删除的图书");
                    }
                    break;
                case 'saveBook':
                    layer.open({
                        type: 1,
                        area: ['800px', '560px'],
                        shadeClose: true, //点击遮罩关闭
                        title: '添加图书',
                        btn: ['确定', '取消'],
                        content: $('#saveBookFrame'),
                        success: function (index, layero){
                            $("#save-title").val("");
                            $("#preview_img1").attr("src","");
                            $("#save_imgFile").val("");
                            $("#save-press").val("");
                            $("#save-author").val("");
                            $("#save-price").val("");
                            $("#save-type").val("计算机类");
                            $("#save-stock").val("");
                            $("#save-location").val("");
                            form.render();
                        },
                        yes: function (index, layero){
                            var title = $.trim($("#save-title").val());
                            var press = $.trim($("#save-press").val());
                            var author = $.trim($("#save-author").val());
                            var price = $.trim($("#save-price").val());
                            var type = $.trim($("#save-type").val());
                            var stock = $.trim($("#save-stock").val());
                            var location = $.trim($("#save-location").val());
                            if(title===''){
                                layer.msg("请输入图书名");
                                return false;
                            }
                            if(!(reNumber.test(price))){
                                layer.msg("请输入正确的价格");
                                return false;
                            }
                            if(!(reNumber.test(stock))){
                                layer.msg("请输入正确的库存数量");
                                return false;
                            }
                            if(!(reLocation.test(location))){
                                layer.msg("请输入正确的位置信息");
                                return false;
                            }

                            var formFile = new FormData(document.getElementById('saveBookForm'));
                            formFile.append("title", title);
                            formFile.append("press", press);
                            formFile.append("author", author);
                            formFile.append("price", price);
                            formFile.append("type", type);
                            formFile.append("stock", stock);
                            formFile.append("location", location);
                            console.log(formFile);
                            $.ajax({
                                url : '${pageContext.request.contextPath}/book/saveBook.do',
                                type : 'post',
                                dataType : 'json',
                                data : formFile,
                                cache: false,
                                processData: false,   // 用于对参数进行序列化处理，这里必须设为false
                                contentType:false,
                                success : function(n) {
                                    if (n.success) {
                                        layer.msg("添加图书《"+title+"》成功");
                                        reload();
                                        layer.close(index);
                                    }else {
                                        layer.msg("添加图书《"+title+"》失败,"+n.msg);
                                    }
                                }
                            });
                        },
                        end: function (res) {
                            $("#saveBookFrame").css("display",'none');
                        }
                    });
                    break;
            };
        });
        function reload(){
            tableIns.reload({
                where: {
                    "title": $('#search-title').val(),
                    "press": $('#search-press').val(),
                    "author": $('#search-author').val(),
                    "minPrice": $('#search-minPrice').val(),
                    "maxPrice": $('#search-maxPrice').val(),
                    "stock": $('#search-stock').is(":checked"),
                    "type": searchType.getValue('name')
                }
                ,page: {
                    curr: 1 //重新从第 1 页开始
                }
            });
        }
    });
</script>
</body>
<div style="display:none;" id="saveBookFrame">
    <form id="saveBookForm" class="layui-form layui-form-pane" style="width: 90%;padding: 30px;" enctype="multipart/form-data" >
        <div class="layui-form-item">
            <label class="layui-form-label">图书名</label>
            <div class="layui-input-block">
                <input class="layui-input" id="save-title" autocomplete="off"  placeholder="请输入图书名(无需书名号)，例：java核心技术（上）">
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">出版社</label>
                <div class="layui-input-inline">
                    <input class="layui-input" id="save-press" autocomplete="off"  placeholder="请输入出版社全称">
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label">作者</label>
                <div class="layui-input-inline">
                    <input class="layui-input" id="save-author" autocomplete="off"  placeholder="请输入作者名">
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">类别</label>
                <div class="layui-input-inline">
                    <select id="save-type" lay-filter="type">
                    <c:forEach items="${applicationScope.typeList}" var="a">
                        <option value="${a.value}">${a.value}</option>
                    </c:forEach>
                    </select>
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label">价格</label>
                <div class="layui-input-inline">
                    <input class="layui-input" id="save-price" autocomplete="off"  placeholder="请输入价格">
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">库存</label>
                <div class="layui-input-inline">
                    <input class="layui-input" id="save-stock" autocomplete="off"  placeholder="请输入库存">
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label">位置</label>
                <div class="layui-input-inline">
                    <input class="layui-input" id="save-location" autocomplete="off"  placeholder="请输入位置，例如：A-1-1">
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">图片</label>
                <div class="layui-input-inline">
                    <div style="display:flex;justify-content: center;align-items: center;height: 38px;border:#EEEEEE 1px solid">
                        <input id="save_imgFile" name="imgFile" type="file" data-allowed-file-extensions='["jpg","png"]' maxFileCount=1>
                    </div>
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-inline">
                <div class="layui-input-inline">
                    <img id="preview_img1" src="" style="width:100%">
                </div>
            </div>
        </div>
    </form>
</div>
<div style="display:none;" id="editBookFrame">
    <form id="editBookForm" class="layui-form layui-form-pane" style="width: 90%;padding: 30px;" enctype="multipart/form-data" >
        <div class="layui-form-item">
            <label class="layui-form-label">图书名</label>
            <div class="layui-input-block">
                <input class="layui-input" id="edit-title" autocomplete="off"  placeholder="请输入图书名(无需书名号)，例：java核心技术（上）">
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">出版社</label>
                <div class="layui-input-inline">
                    <input class="layui-input" id="edit-press" autocomplete="off"  placeholder="请输入出版社全称">
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label">作者</label>
                <div class="layui-input-inline">
                    <input class="layui-input" id="edit-author" autocomplete="off"  placeholder="请输入作者名">
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">类别</label>
                <div class="layui-input-inline">
                    <select id="edit-type" lay-filter="type">
                    <c:forEach items="${applicationScope.typeList}" var="a">
                        <option value="${a.value}">${a.value}</option>
                    </c:forEach>
                    </select>
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label">价格</label>
                <div class="layui-input-inline">
                    <input class="layui-input" id="edit-price" autocomplete="off"  placeholder="请输入价格">
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">库存</label>
                <div class="layui-input-inline">
                    <input class="layui-input" id="edit-stock" autocomplete="off"  placeholder="请输入库存">
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label">借出</label>
                <div class="layui-input-inline">
                    <input class="layui-input" id="edit-borrows" autocomplete="off"  placeholder="请输入已借数量">
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">图片</label>
                <div class="layui-input-inline">
                    <div style="display:flex;justify-content: center;align-items: center;height: 38px;border:#EEEEEE 1px solid">
                        <input id="edit_imgFile" name="imgFile" type="file" data-allowed-file-extensions='["jpg","png"]' maxFileCount=1>
                    </div>
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label">位置</label>
                <div class="layui-input-inline">
                    <input class="layui-input" id="edit-location" autocomplete="off"  placeholder="请输入位置，例如：A-1-1">
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-inline">
                <div class="layui-input-inline">
                    <img id="preview_img2" src="" style="width:100%">
                </div>
            </div>
        </div>
    </form>
</div>
</html>